<?php

namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Request;
use think\Session;
use think\View;

class Base extends Controller
{
    protected $columnData;
    protected $systemConfig;

    //构造函数
    public function _initialize()
    {

        //列表或者搜索没有数据时显示
        $this->assign('empty', '<span class="empty">暂时没有数据</span>');

    }


    //前置操作
    protected $beforeActionList = [
        'getColumnList',
        'getSystem',
        'getArticleCount',
        'getWorksCount',
    ];

    //获取主栏目
    protected function getColumnList()
    {
        $this->columnData = infinite_classify('column');
//        halt($this->columnData );
        View::share('column', $this->columnData);
    }

    //获取系统配置信息
    protected function getSystem()
    {
        $data = Db::name('system')->select();

        foreach ($data as $k => $v) {
            $this->systemConfig[$v['en_name']] = json_decode($v['config'], TRUE);
            View::share($v['en_name'], json_decode($v['config'], TRUE));
        }
    }

    //获取文章总数
    protected function getArticleCount()
    {
        $data = Db::name('article')->count();

        View::share('article_count', $data);

    }

    //获取项目总数
    protected function getWorksCount()
    {
        $data = Db::name('works')->count();

        View::share('works_count', $data);
    }


    /*获取推荐标签*/
    protected static function recommend($tableName = 'article')
    {
        $map['istop'] = 1; //推荐为1
        $keyArr = Db::name($tableName)->where($map)->order(['create_time' => 'desc', 'id' => 'desc', 'hits' => 'desc'])->field('keywords')->limit(50)->select();
        $kid_vkeywords = array_column($keyArr, 'keywords');

        $keywords = [];
        foreach ($kid_vkeywords as $k => $v) {
            $temp = explode(',', $v);
            if (count($temp) > 1) {
                foreach ($temp as $kk => $vv) {
                    $keywords[] = $vv;
                }
            } else {
                $keywords[] = $v;
            }
        }
        $keywords = array_slice(array_unique(array_filter($keywords)), 0, 15);
        View::share('keywords', $keywords);
    }

    /*获取上一篇，下一篇*/
    protected static function get_pre_next($column_id = 0, $current_id = 0, $tableName = 'article')
    {
        $preNextData = [];
        $preNextData['tableName'] = $tableName;

        $map['column_id'] = ['=', $column_id];
        //上一篇
        $map['id'] = ['<', $current_id];
        $preNextData['pre'] = Db::name($tableName)->where($map)->order('id', 'desc')->field('id')->find();
        //下一篇
        $map['id'] = ['>', $current_id];
        $preNextData['next'] = Db::name($tableName)->where($map)->order('id', 'asc')->field('id')->find();

        View::share('preNextData', $preNextData);

    }


    /*空操作时调用
     * */
    public function _empty(Request $request)
    {
        $this->error($request->action() . '该方法不存在!', 'Index/index');
    }
}
